package com.cskaoyan.config;

import com.cskaoyan.token.MallToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

// 重写父类的doAuthenticate()方法，从而可以根据token的类型来选择不同的realm
public class CustomAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        Collection<Realm> originRealms = this.getRealms();

        MallToken token = (MallToken) authenticationToken;
        String type = token.getType();

        // 狸猫换太子
        ArrayList<Realm> realms = new ArrayList<>();

        for (Realm originRealm : originRealms) {
            if (originRealm.getName().toLowerCase().contains(type)) {
                realms.add(originRealm);
            }
        }

        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);
    }
}
